﻿
//初始化为无信号

using System.Security.Cryptography.X509Certificates;

ManualResetEvent manualResetEvent = new ManualResetEvent(false);

Thread[] threads = new Thread[4];

for(int i=0;i<4;i++)
{
    threads[i] = new Thread(Worker);
    threads[i].Start(i);
}
//for (int i = 0; i < 4; i++)
//{
//    threads[i].Join();
//}

Thread.Sleep(1000);

//设置信号量，唤醒全部线程
manualResetEvent.Set();


Thread.Sleep(2000);

//重置
manualResetEvent.Reset();
//第二次设置信号量，唤醒全部线程
manualResetEvent.Set();

Thread.Sleep(1000);

Console.WriteLine("主线程执行完毕!");
Console.ReadLine();

void Worker(object? obj)
{
    //Console.WriteLine($"线程:{obj},开始第一次等待信号");
    manualResetEvent.WaitOne();    
    Console.WriteLine($"{GetCurrentTime()}---线程:{obj}，拿到第一次信号，开始工作");
    Thread.Sleep(2000);
    manualResetEvent.WaitOne();
    Console.WriteLine($"{GetCurrentTime()}---线程:{obj}，拿到第二次信号，开始工作");
    Thread.Sleep(2000);
    Console.WriteLine($"{GetCurrentTime()}---线程:{obj}，执行完毕!");
}

string GetCurrentTime()
{
    return DateTime.Now.ToString("yyyy-mm-dd HH:mm:ss:fff");
}